package app;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;


public class AudioPlayer {
	private static AudioPlayer instance;

	private Queue<File> queue;

	//private Player player;
	private PlayerCore player;
	private File file;

	// 0 = stopped, 1 = paused, 2 = playing
	private final int STOPPED = 0;
	private final int PAUSED = 1;
	private final int PLAYING = 2;
	private int status = STOPPED;

	private String trackName = "";

	private AudioPlayer() {
		queue = new LinkedList<File>();
		player = new PlayerCore();
	}

	public static synchronized AudioPlayer getInstance() {
		if (instance == null) {
			instance = new AudioPlayer();
		}
		return instance;
	}

	public ArrayList<File> getPlaylist() {
		ArrayList<File> playlist = new ArrayList<File>();
		Iterator<File> iter = queue.iterator();

		while (iter.hasNext()) {
			playlist.add(iter.next());
		}

		return playlist;
	}

	public void addtrack(File file) {
		queue.offer(file);
	}

	public void playNext() {
		System.out.println("NEXT SONG");
		player.stop();
	}

	public void stopPlaying() {
		System.out.println("STOP PLAYING");
		status = STOPPED;
		trackName = "";
		player.stop();
	}

	public void setVolume(int percent) {
		player.adjustVolume(percent);
	}

	public int getVolume() {
		return player.getVolume();
	}

	public void play() {
		System.out.println("START PLAYING");
		while (!queue.isEmpty()) {
			file = queue.poll();
			player.open(file);
			status = PLAYING;
			trackName = file.getName();
			player.play();
			
			if(status == STOPPED){
				break;
			}
		}
		
		if(status == PLAYING){
			status = STOPPED;
			trackName = "";
		}
	}



	public int getStatus() {
		return status;
	}

	public String getTrackName() {
		return trackName;
	}
	
	public int getProgress() {
		return player.getProgress();
	}

}
